﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KorleBu.Application_Classes;
using System.Drawing;

namespace KorleBu
{
    public partial class Requisitions : System.Web.UI.Page
    {
        #region Class State Variables
            DataSet ds = new DataSet();
            Presentation presentation = new Presentation();
            DataTable dt = new DataTable();
            public DataSet items = new DataSet();
            public Application_Classes.ItemSearch itemSearch = new Application_Classes.ItemSearch();
        #endregion

        #region PageLoad

        protected void Page_Load(object sender, EventArgs e)
        {
            //keep clean error message on load; other methods occur after load so they will fill in the error as needed.
            lblMasterError.Text = "";

            #region Aarons Stuff
            //if the user didn't log in, but browsed to this page redirect them to the login page.
            if (GetSessionID() == null || GetSessionID() == "")
            {
                Response.Redirect("~/Login.aspx", true);
            }
            lblLoggedInUser.Text = "You are logged in as " + GetFirstName() + " " + GetLastName();
            //if the user doesn't have admin privileges send them back to the home page
            //if (Global.loggedInUser.getIsAdmin() == false)
            //{
            //    Response.Redirect("~/Home.aspx", true);
            //}

            //show a message for pending tasks if the given user has tasks to do.  
            //This should only apply to store managers, general managers, CEOs, and Procurement
            if (GetIsStoreManager())
            {
                //ds = presentation.GetPendingRequests();
                //if (ds.Tables.Count > 0) // If the method returned successfully
                //{
                //    if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                //    {
                //        lblError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                //    }
                //    else
                //    {
                //lblSideBarContent.Text = "**You have pending satellite store requests to handle.**";
                //    }
                //}
            }
            else if (GetIsGeneralManager())
            {
                //ds = presentation.GetRequisitionsByGMStatus();
                //if (ds.Tables.Count > 0) // If the method returned successfully
                //{
                //    if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                //    {
                //        lblError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                //    }
                //    else
                //    {
                //lblSideBarContent.Text = "**You have pending requisitions to handle.**";
                //    }
                //}
            }
            else if (GetIsCEO())
            {
                //ds = presentation.GetRequisitonsByCEOStatus();
                //if (ds.Tables.Count > 0) // If the method returned successfully
                //{
                //    if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                //    {
                //        lblError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                //    }
                //    else
                //    {
                //lblSideBarContent.Text = "**You have pending requisitions to handle.**";
                //    }
                //}
            }
            else if (GetIsProcurement())
            {
                //ds = presentation.getRequisitionsByProcurementStatus();
                //if (ds.Tables.Count > 0) // If the method returned successfully
                //{
                //    if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                //    {
                //        lblError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                //    }
                //    else
                //    {
                //lblSideBarContent.Text = "**You have pending requisition orders to handle.**";
                //    }
                //}
            }
            else
                //lblSideBarContent.Text = "At any time, you can click on the logo above to return to this home page. Please click the \"logout\" button to end the program when you are finished working.";
            #endregion

            if (!IsPostBack)
            {
                ds = presentation.GetCategory();
                ddlItemCategory.DataSource = ds.Tables[1];
                ddlItemCategory.DataTextField = "itemCategoryName";
                ddlItemCategory.DataValueField = "itemCategoryID";
                ddlItemCategory.DataBind(); 

                populateRequestDescriptionDdl();
            }

            ds = presentation.CheckOpenRequest(GetStoreID());

            if (ds.Tables[0].Rows[0][0].ToString() == "")
            {
                lblRequestID.Text = ds.Tables[1].Rows[0][0].ToString();
                lblRequestDate.Text = ds.Tables[1].Rows[0][1].ToString();
                lblDescription.Text = ds.Tables[1].Rows[0][2].ToString();
                mvRequest.ActiveViewIndex = 1;
                if (!IsPostBack)
                {
                    ds = presentation.GetRequestItemsByRequestID(Convert.ToInt32(ds.Tables[1].Rows[0][0].ToString()), GetStoreID());
                    if (ds.Tables[0].Rows[0][0].ToString() == "")
                    {
                        gvRequest.DataSource = ds.Tables[1];
                        gvRequest.DataBind();
                    }
                    else
                    {
                        gvRequest.DataSource = null;
                        gvRequest.DataBind();
                    }
                }
            }
            else
            {
                mvRequest.ActiveViewIndex = 0;
            }

            ds = presentation.GetRequestsByStoreID(GetStoreID());
            if (ds.Tables[0].Rows[0][0].ToString() == "")
            {
                gvViewRequests.DataSource = ds.Tables[1];
                gvViewRequests.DataBind();


                // Set the color of the statuses
                foreach (GridViewRow gvr in gvViewRequests.Rows)
                {
                    Label lblStatusName = gvr.FindControl("lblStatusName") as Label;
                    String status = lblStatusName.Text;
                    if (status == "Pending")
                    {
                        lblStatusName.ForeColor = Color.DarkOrange;
                    }
                    else if (status == "Filled")
                    {
                        lblStatusName.ForeColor = Color.DarkGreen;
                    }
                    else if (status == "Denied")
                    {
                        lblStatusName.ForeColor = Color.DarkRed;
                    }
                }
            }
            else
            {
                lblNoRequest.Text = "No current requests";
                gvViewRequests.DataSource = null;
                gvViewRequests.DataBind();
            }
            
            
            if (gvRequest.Rows.Count <= 0)
            {
                btnSubmitRequest.Visible = false;
                lblRequestMissing.Text = "There are currently no items for this request";
            }
            else
            {
                btnSubmitRequest.Visible = true;
                lblRequestMissing.Text = "";
            }
        }
       
        #endregion

        #region Request View
            protected void btnSelectNewRequest_Click(object sender, EventArgs e)
            {
                mvViewRequests.SetActiveView(vViewRequest);
            }

            protected void gvViewRequests_RowCommand(object sender, GridViewCommandEventArgs e)
            {


                if (e.CommandName == "Select")
                {
                    // Retrieve the row index stored in the 
                    // CommandArgument property.
                    int index = Convert.ToInt32(e.CommandArgument);

                    // Retrieve the row that contains the button 
                    // from the Rows collection.
                    GridViewRow row = gvViewRequests.Rows[index];

                    lblViewRequestID.Text = row.Cells[0].Text;
                    Session["RequestID"] = lblViewRequestID.Text;
                    lblViewDate.Text = row.Cells[2].Text;
                    lblViewDescription.Text = row.Cells[1].Text;

                    gvViewRequestItems.DataSource = presentation.GetRequestItemsByRequestID(Convert.ToInt32(gvViewRequests.Rows[index].Cells[0].Text), GetStoreID()).Tables[1];
                    gvViewRequestItems.DataBind();
                    mvViewRequests.SetActiveView(vViewRequestItems);

                    // Set the color of the statuses
                    foreach (GridViewRow gvr in gvViewRequestItems.Rows)
                    {
                        Label lblStatusName = gvr.FindControl("lblStatusName") as Label;
                        String status = lblStatusName.Text;
                        if (status == "Pending" || status == "Ready" || status.Contains("Partially"))
                        {
                            lblStatusName.ForeColor = Color.DarkOrange;
                        }
                        else if (status == "Filled" || status == "Picked-Up")
                        {
                            lblStatusName.ForeColor = Color.DarkGreen;
                        }
                        else if (status == "Denied")
                        {
                            lblStatusName.ForeColor = Color.DarkRed;
                        }
                    }
                }
            }
        #endregion

        #region Request Generation

            #region Buttons

                protected void btnSearch_Click(object sender, EventArgs e)
                {
                    gvItemSearch.EditIndex = -1;
                    Session.Remove("ItemName");
                    Session.Remove("Items");
                    itemSearch.searchMethod = 1;
                    itemSearch.categorySearched = Convert.ToInt32(ddlItemCategory.SelectedValue);
                    GetItemName();
                    ds = presentation.GetItemByCategory(itemSearch.categorySearched);
                    items = ds;
                    ItemList();
                    populateItemGridView(items);

                }

                protected void btnSearchItemName_Click(object sender, EventArgs e)
                {
                    gvItemSearch.EditIndex = -1;
                    Session.Remove("ItemName");
                    Session.Remove("Items");
                    itemSearch.searchMethod = 2;
                    itemSearch.itemSearched = txtItemName.Text;
                    GetItemName();
                    ds = presentation.GetItemByName(itemSearch.itemSearched);
                    items = ds;
                    ItemList();
                    populateItemGridView(items);
                }

                protected void btnCreateRequest_Click(object sender, EventArgs e)
                {
                    //Validate("Create");
                    dt = presentation.CreateRequest(GetStoreID(), ddlDescription.Text).Tables[1];

                    lblRequestID.Text = dt.Rows[0][0].ToString();
                    lblRequestDate.Text = dt.Rows[0][1].ToString();
                    lblDescription.Text = dt.Rows[0][2].ToString();

                    mvRequest.ActiveViewIndex = 1;
                        
                }

                protected void btnSubmitRequest_Click(object sender, EventArgs e)
                {
                    bool okToSubmit = false;

                    if ((ddlDescription.Text == "Other - please specify" && txtOtherSpecified.Text == ""))
                    {
                        lblDescriptionError.Text = "Please specify a new reason.";
                        lblDescriptionError.Visible = true;
                    }
                    else if (ddlDescription.Text == "Need to change description")
                    {
                        lblDescriptionError.Text = "Please change the description before submitting request.";
                        lblDescriptionError.Visible = true;
                        txtOtherSpecified.Visible = false;
                        lblOtherSpecified.Visible = false;
                        lblAstrisk.Visible = true;
                    }
                    else
                    {
                        okToSubmit = true;
                    }

                    if (okToSubmit)
                    {
                        if (ddlDescription.Text == "Other - please specify")
                        {
                            presentation.ChangeRequestDescription(Convert.ToInt32(lblRequestID.Text), txtOtherSpecified.Text);
                        }
                        else
                        {
                            presentation.ChangeRequestDescription(Convert.ToInt32(lblRequestID.Text), ddlDescription.Text);
                        }
                        presentation.SubmitRequest(Convert.ToInt32(lblRequestID.Text));
                        TabContainer.ActiveTabIndex = 0;
                        Response.Redirect("Requests.aspx");
                    }
                   
                    
                }
                //Delete the selected Request if there are no items in the request, otherwise delete any items first then delete the request
                protected void btnCancelRequest_Click(object sender, EventArgs e)
                {
                    //Check first if there are items in a request to delete
                    if (gvRequest.Rows.Count > 0)
                    {
                        for (int i = 1; i <= gvRequest.Rows.Count; i++)
                        {
                            int index = i - 1;
                            GridViewRow row = gvRequest.Rows[index];
                            presentation.DeleteRequestItem(Convert.ToInt32(lblRequestID.Text), Convert.ToInt32((row.FindControl("lblItemID") as Label).Text));
                        }
                    }

                    presentation.DeleteRequest(Convert.ToInt32(lblRequestID.Text));
                    Response.Redirect("Requests.aspx");
                }

            #endregion

            #region gvItemSearch Controls
                protected void populateItemGridView(DataSet i)
                {
                    if (i.Tables[0].Rows[0][0].ToString() != "")
                    {
                        //string me = ds.Tables[0].Rows[0][0].ToString();   //was used to be the error label
                        lblMyError.Text = "No items found";

                        gvItemSearch.DataSource = null;
                        gvItemSearch.DataBind();
                    }
                    else
                    {
                        gvItemSearch.DataSource = i.Tables[1];
                        gvItemSearch.DataBind();

                        if (gvItemSearch.PageIndex == gvItemSearch.PageCount - 1)
                        {
                            ((LinkButton)gvItemSearch.BottomPagerRow.FindControl("lnkNextPage")).Enabled = false;
                        }
                        else
                        {
                            ((LinkButton)gvItemSearch.BottomPagerRow.FindControl("lnkNextPage")).Enabled = true;
                        }


                        if (gvItemSearch.PageIndex == 0)
                        {
                            ((LinkButton)gvItemSearch.BottomPagerRow.FindControl("lnkPrevPage")).Enabled = false;
                        }
                        else
                        {
                            ((LinkButton)gvItemSearch.BottomPagerRow.FindControl("lnkPrevPage")).Enabled = true;
                        }
                        lblMyError.Text = "";
                    }

                }
                protected void gvItemSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
                {
                    items = ItemList();
                    gvItemSearch.PageIndex = e.NewPageIndex;
                    gvItemSearch.DataBind();
                    populateItemGridView(items);
                }
                protected void gvItemSearch_RowCommand(object sender, GridViewCommandEventArgs e)
                {
                    if (e.CommandName == "Add")
                    {
                        // Retrieve the row index stored in the 
                        // CommandArgument property.
                        int index = Convert.ToInt32(e.CommandArgument);


                        // Retrieve the row that contains the button 
                        // from the Rows collection.
                        GridViewRow row = gvItemSearch.Rows[index];

                        int Num;
                        bool isNum = int.TryParse(((TextBox)row.FindControl("txtQuantity")).Text, out Num);
                        if (!isNum)
                        {
                            lblMyError.Text = "Please enter a number";
                        }
                        else if (Num < 1)
                        {
                            lblMyError.Text = "Enter amount greater then 0";
                        }
                        else if (((TextBox)row.FindControl("txtQuantity")).Text == "")
                        {
                            lblMyError.Text = "Must enter a valid quantity";
                        }

                        else
                        {
                            
                            ds = presentation.AddItemToRequest(Convert.ToInt32(lblRequestID.Text), Convert.ToInt32((row.FindControl("lblItemID") as Label).Text), Convert.ToInt32(((TextBox)row.FindControl("txtQuantity")).Text));

                            if (ds.Tables[0].Rows[0][0].ToString() != "")
                            {
                                lblMyError.Text = ds.Tables[0].Rows[0][0].ToString();
                            }
                            else
                            {
                                lblMyError.Text = "";
                            }

                            ((TextBox)row.FindControl("txtQuantity")).Text = "";

                            btnSubmitRequest.Visible = true;
                            lblRequestMissing.Text = "";
                            ds = presentation.GetRequestItemsByRequestID(Convert.ToInt32(lblRequestID.Text), GetStoreID());
                            gvRequest.DataSource = ds.Tables[1];
                            gvRequest.DataBind();
                        }
                        
                    }
                }
            #endregion

        #endregion

        #region Session Control
            //Create and retrieve session
            private Application_Classes.ItemSearch GetItemName()
            {
                if (Session["ItemName"] == null)
                    Session.Add("ItemName", itemSearch);

                return (Application_Classes.ItemSearch)Session["ItemName"];
            }

            private DataSet ItemList()
            {
                if (Session["Items"] == null)
                    Session.Add("Items", items);
                return (DataSet)Session["Items"];
            }

            private int GetStoreID()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getStoreId();
            }

            private int GetUserID()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getUserId();
            }

            private string GetFirstName()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getFirstName();
            }
            private string GetLastName()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getLastName();
            }
            private string GetSessionID()
            {
                try
                {
                    User lg = (User)Session["LoggedInUser"];
                    return lg.getSessionId();
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                    return null;
                }
            }
            private bool GetIsAdmin()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getIsAdmin();
            }
            private bool GetIsGeneralManager()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getIsGeneralManager();
            }
            private bool GetIsStoreManager()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getIsStoreManager();
            }
            private bool GetIsStoreKeeper()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getIsStoreKeeper();
            }
            private bool GetIsSubUnitClerk()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getIsSubUnitClerk();
            }
            private bool GetIsAccounting()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getIsAccounting();
            }
            private bool GetIsProcurement()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getIsProcurement();
            }
            private bool GetIsCEO()
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getIsCEO();
            }

        #endregion Session Control 

            protected void gvRequest_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "Remove")
                {
                    // Retrieve the row index stored in the 
                    // CommandArgument property.
                    int index = Convert.ToInt32(e.CommandArgument);


                    // Retrieve the row that contains the button 
                    // from the Rows collection.
                    GridViewRow row = gvRequest.Rows[index];

                    presentation.DeleteRequestItem(Convert.ToInt32(lblRequestID.Text), Convert.ToInt32((row.FindControl("lblItemID") as Label).Text));
                    ds = presentation.GetRequestItemsByRequestID(Convert.ToInt32(lblRequestID.Text), GetStoreID());
                    if (ds.Tables[0].Rows[0][0].ToString() == "")
                    {
                        gvRequest.DataSource = ds.Tables[1];
                    }
                    else
                    {
                        lblRequestMissing.Text = "There are currently no items for this request";
                        btnSubmitRequest.Visible = false;
                        gvRequest.DataSource = null;
                    }
                    gvRequest.DataBind();

                }
            }

            protected void gvRequest_RowEditing(object sender, GridViewEditEventArgs e)
            {
                gvRequest.EditIndex = e.NewEditIndex;
                ds = presentation.GetRequestItemsByRequestID(Convert.ToInt32(lblRequestID.Text), GetStoreID());
                if (ds.Tables[0].Rows[0][0].ToString() == "")
                {
                    gvRequest.DataSource = ds.Tables[1];
                    gvRequest.DataBind();
                    //GridViewRow row = gvRequest.Rows[e.NewEditIndex];
                    //disable the delete button while editing; I decided that the 
                    //whole list shouldn't be able to delete something whenever any one item is being edited.
                    //Change GridView enabled/visible properties only after calling DataBind();
                    //Adam Venezia 11-21-12
                    //row.Cells[5].Enabled = false;
                    gvRequest.Columns[5].Visible = false;
                }
                else
                {
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();
                    gvRequest.DataBind(); //bind null to clear out old grid
                }
            }

            protected void gvRequest_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                gvRequest.EditIndex = -1;
                ds = presentation.GetRequestItemsByRequestID(Convert.ToInt32(lblRequestID.Text), GetStoreID());
                if (ds.Tables[0].Rows[0][0].ToString() == "")
                {
                    gvRequest.DataSource = ds.Tables[1];
                    gvRequest.DataBind();
                    //GridViewRow row = gvRequest.Rows[e.RowIndex];
                    //row.Cells[5].Enabled = true;
                    gvRequest.Columns[5].Visible = true;
                }
                else
                {
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();
                    gvRequest.DataBind(); //bind null to clear out old grid
                }
                
            }

            protected void gvRequest_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                GridViewRow row = gvRequest.Rows[e.RowIndex];
                int qty = Convert.ToInt32(((TextBox)row.FindControl("txtEditRequestQty")).Text);

                ds = presentation.ModifyRequest(Convert.ToInt32(lblRequestID.Text), Convert.ToInt32((row.FindControl("lblItemID") as Label).Text), qty);

                gvRequest.EditIndex = -1;
                ds = presentation.GetRequestItemsByRequestID(Convert.ToInt32(lblRequestID.Text), GetStoreID());
                
                if (ds.Tables[0].Rows[0][0].ToString() == "")
                    gvRequest.DataSource = ds.Tables[1];
                else
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();

                gvRequest.DataBind();
                gvRequest.Columns[5].Visible = true;
            }
            
            /// <summary>
            /// Takes evaluations of columns in a data bound GridView to calculate cost * qty for a row.
            /// </summary>
            /// <param name="cost">Cost of an item in a GridViewRow.</param>
            /// <param name="qty">Quantity of an item in a GridViewRow.</param>
            /// <returns>String formatted value of cost * qty.</returns>
            public String CalcCost(Object cost, Object qty)
            {
                //DataBind functions always pass in generic objects, not strongly typed objects
                Double dCost = Convert.ToDouble(cost);
                Double dQty = Convert.ToDouble(qty);

                return String.Format("{0:0.00}", (dCost * dQty));
            }

            private void populateRequestDescriptionDdl()
            {
                DataSet ds = presentation.GetSubUnits();
                DataTable descriptions = new DataTable();
                descriptions.Columns.Add("subUnitName");
                descriptions.Rows.Add("Need to change description");

                if (ds.Tables[0].Rows[0][0].ToString() != "")
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();
                else
                {

                    foreach (DataRow row in ds.Tables[1].Rows)
                    {
                        String desc = row["subUnitName"].ToString() + " To Central Store";
                        descriptions.Rows.Add(desc);
                    }

                    descriptions.Rows.Add("Other - please specify");
                    ddlDescription.DataSource = descriptions;
                    ddlDescription.DataTextField = "subUnitName";
                    ddlDescription.DataBind();
                }
            }

            protected void TabContainer_ActiveTabChanged(object sender, EventArgs e)
            {
                // Reload stuff from database
            }

            protected void ddlDescription_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (ddlDescription.Text == "Need to change description")
                {
                    lblDescriptionError.Text = "Please change the description before submitting request.";
                    lblDescriptionError.Visible = true;
                    txtOtherSpecified.Visible = false;
                    lblOtherSpecified.Visible = false;
                    lblAstrisk.Visible = true;
                }
                else if (ddlDescription.Text == "Other - please specify" && txtOtherSpecified.Text == "")
                {
                    txtOtherSpecified.Visible = true;
                    lblOtherSpecified.Visible = true;
                    lblDescriptionError.Visible = false;
                    lblAstrisk.Visible = true;
                }
                else
                {
                    lblDescriptionError.Visible = false;
                    txtOtherSpecified.Visible = false;
                    lblOtherSpecified.Visible = false;
                    lblAstrisk.Visible = false;
                }
                
            }

            //Created by Jason Vance 10-26-2012
            /// <summary>
            /// This will sort the item searching gridview
            /// </summary>
            protected void gvItemSearch_Sorting(object sender, GridViewSortEventArgs e)
            {
                try
                {
                    // Sort the data
                    if (GridViewSortDirection == SortDirection.Ascending)
                    {
                        GridViewSortDirection = SortDirection.Descending;
                        SortGridView(e.SortExpression, "DESC");
                    }
                    else
                    {
                        GridViewSortDirection = SortDirection.Ascending;
                        SortGridView(e.SortExpression, "ASC");
                    }
                }
                catch (Exception ex)
                {
                }
            }

            //Created by Jason Vance 10-26-2012
            /// <summary>
            /// This will keep track of the sort direction between postbacks
            /// </summary>
            public SortDirection GridViewSortDirection
            {
                get
                {
                    if (Session["sortDirection"] == null)
                        Session["sortDirection"] = SortDirection.Ascending;

                    return (SortDirection)Session["sortDirection"];
                }
                set { Session["sortDirection"] = value; }
            }

            //Created by Jason Vance 10-26-2012
            /// <summary>
            /// This does the actual work of sorting the data that will be put into gvItemSearch
            /// </summary>
            private void SortGridView(string sortExpression, string direction)
            {
                try
                {
                    // Get the current list of items
                    ds = ItemList();
                    DataTable dt = ds.Tables[1];

                    // Sort that list
                    DataView dv = new DataView(dt);
                    dv.Sort = sortExpression + " " + direction;

                    // Replace the current list with the new sorted one
                    ds.Tables.RemoveAt(1);
                    ds.Tables.Add(dv.ToTable());
                    Session.Add("Items", ds);

                    // Bind it to the gridview
                    gvItemSearch.DataSource = dv;
                    gvItemSearch.DataBind();
                }
                catch (Exception ex)
                {
                }
            }
    }
}